package org.seeplnframework.skyeye.common.trace;

import io.jaegertracing.internal.JaegerSpanContext;
import io.opentracing.Span;
import io.opentracing.SpanContext;
import io.opentracing.Tracer;
import lombok.extern.slf4j.Slf4j;
import org.seeplnframework.skyeye.common.util.SpringUtils;

/**
 * @author ly
 * @date 2022/12/28
 */
@Slf4j
public class TraceContext {

    public static String traceId() {
        String noTraceId = "N/A";
        try {
            Tracer tracer = SpringUtils.getBean(Tracer.class);
            if (tracer == null) {
                //log.info("cur tracer is null. get trace id fail.");
                return noTraceId;
            }
            Span span = tracer.activeSpan();
            if (span == null) {
                //log.info("cur active span is null. get trace id fail.");
                return noTraceId;
            }
            SpanContext context = span.context();
            if (context instanceof JaegerSpanContext) {
                return ((JaegerSpanContext) context).getTraceId();
            }
            return tracer.activeSpan().getBaggageItem("trace_id");
        } catch (Exception e) {
            log.warn("get trace id occur exception, stack is : [{}]", e.getStackTrace());
            return noTraceId;
        }
    }
}
